package stat

import (
	"data_summary/common/models/stat"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type StatDayOrderDao struct {
	db *gorm.DB
}

func NewStatDayOrder(db *gorm.DB) *StatDayOrderDao {
	dao := &StatDayOrderDao{
		db: db,
	}
	return dao
}
func (c *StatDayOrderDao) TableName(suffix string) *StatDayOrderDao {
	c.db = c.db.Table("tj_stat_day_order_" + suffix)
	return c
}

// 创建表
func (c *StatDayOrderDao) CreateTable(tableName string) (err error) {
	exist := c.db.Migrator().HasTable(tableName)
	//fmt.Print("是否存在", exist)
	if exist == true {
		return nil
	}
	sql := "CREATE TABLE `" + tableName + "` (" +
		"`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT," +
		"`standard_date` date NOT NULL COMMENT '日期'," +
		"`company_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '商家id'," +
		"`shop_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '门店id'," +
		"`proid` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '商品id'," +
		"`cate_id` int(11) NOT NULL DEFAULT '0' COMMENT '分类id'," +
		"`day_num` tinyint(10) unsigned NOT NULL DEFAULT '0' COMMENT '相差天数'," +
		"`supplier_id` int(11) DEFAULT NULL COMMENT '代理商ID'," +
		" `num` decimal(11,2) NOT NULL DEFAULT '0.00' COMMENT '商品销量'," +
		"`sum_price` decimal(10,2) unsigned DEFAULT '0.00' COMMENT '总销售金额'," +
		"`sum_cost_price` decimal(10,2) DEFAULT '0.00' COMMENT '商品总成本'," +
		"`avg_price` decimal(10,2) unsigned DEFAULT '0.00' COMMENT '均价'," +
		"`profit` decimal(10,4) DEFAULT '0.0000' COMMENT '毛利'," +
		"`profit_rate` decimal(10,4) unsigned DEFAULT '0.0000' COMMENT '毛利率'," +
		" `refund_num` int(10) DEFAULT NULL COMMENT '退货数量'," +
		"`refund_sum_price` decimal(10,2) DEFAULT NULL COMMENT '退款金额'," +
		"`create_time` datetime DEFAULT NULL COMMENT '添加时间'," +
		"`update_time` datetime DEFAULT NULL COMMENT '修改时间'," +
		"PRIMARY KEY (`id`)," +
		" UNIQUE KEY `uniq_day` (`standard_date`,`company_id`,`shop_id`,`proid`,`day_num`) USING BTREE" +
		") ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 COMMENT='销售统计表';"
	err = c.db.Exec(sql).Error
	return err
}

// 添加
func (c *StatDayOrderDao) Create(v *stat.StatDayOrder) (id uint, err error) {
	err = c.db.Create(&v).Error
	return v.Id, err
}

// 修改
func (c *StatDayOrderDao) Update(v *stat.StatDayOrder) (id uint, err error) {
	err = c.db.Save(&v).Error
	return v.Id, err
}

// 删除
func (c *StatDayOrderDao) Delete(v *stat.StatDayOrder) (id uint, err error) {
	err = c.db.Delete(&v).Error
	return v.Id, err
}

func (c *StatDayOrderDao) Get(where map[string]interface{}, order string, pageSize int, page int) interface{} {
	var v []stat.StatDayOrder
	c.db.Where(where).Order(order).Limit(pageSize).Offset(page).Find(&v)
	return v
}

func (c *StatDayOrderDao) SetSqlExec(v []stat.StatDayOrder, update []string) error {
	err := c.db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "id"}},
		DoUpdates: clause.AssignmentColumns(update),
	}).Create(&v).Error
	return err
}
